package sort

import (
	"fmt"
	"math/rand"
	"os"
	"time"
)

func GenerateRandomArray(n, rangeL, rangeR int) []int {
	seq := make([]int, n)
	rand.Seed(time.Now().Unix())
	if rangeL > rangeR {
		fmt.Fprintf(os.Stderr, "rangeL must be small than rangeR")
		return nil
	}
	for i := 0; i < n; i++ {
		seq[i] = rand.Intn(rangeR - rangeL) + rangeL
	}
	return seq
}

func IsSorted(seq []int) bool  {
	n := len(seq)
	for i := 0; i < n - 1; i++ {
		if seq[i] > seq[i+1] {
			return false
		}
	}
	return true
}

func TestSort(sortName string, sort func(a []int), seq []int)  {
	start := time.Now()
	sort(seq)
	elapsed := time.Since(start)
	if ! IsSorted(seq) {
		panic("seq is not sorted")
	}
	fmt.Printf("%s took %s\n", sortName, elapsed)
}

func TestSort2(sortName string, sort func(a []int) []int, seq []int)  {
	start := time.Now()
	a := sort(seq)
	elapsed := time.Since(start)
	if ! IsSorted(a) {
		panic("seq is not sorted")
	}
	fmt.Printf("%s took %s\n", sortName, elapsed)
}

func GenerateNearlyOrderedArray(n int, swapTimes int) []int {
	rand.Seed(time.Now().Unix())
	seq := make([]int, n)
	for i := 0; i < n; i++ {
		seq[i] = i
	}
	for i := 0; i < swapTimes; i++ {
		posx := rand.Intn(n)
		posy := rand.Intn(n)
		seq[posx], seq[posy] = seq[posy], seq[posx]
	}
	return seq
}